<template>
    <up-popup :show="show" mode="bottom" round="16" @close="closePicker" :safeAreaInsetBottom="true">
        <view class="time-range-container">
            <!-- 头部操作栏 -->
            <view class="picker-header">
                <text class="btn cancel" @click="closePicker">取消</text>
                <text class="title">{{ title }}</text>
                <text class="btn confirm" @click="handleConfirm">确定</text>
            </view>

            <!-- 时间选择主体 -->
            <view class="picker-body">
                <!-- 开始时间选择 -->
                <view class="time-picker">
                    <text class="picker-label">开始时间</text>
					<picker-view :value="startIndex" @change="handleStartChange" class="picker-view" 
						:indicatorStyle="`height: ${ itemHeight }px;`"
						:style="`height: ${ itemHeight * visibleItemCount }px;width: 300rpx;`"
					 >
						<picker-view-column class="picker-view-column">
							<view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="(h, i) in hours" :key="i" >
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ h }}时</text>
							</view>
						</picker-view-column>
						<picker-view-column class="picker-view-column">
							<view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="(m, i) in minutes" :key="i" >
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ m }}分</text>
							</view>
						</picker-view-column>
					</picker-view>
                </view>
                <text class="separator">至</text>

                <!-- 结束时间选择 -->
                <view class="time-picker">
                    <text class="picker-label">结束时间</text>
                    <picker-view :value="endIndex" @change="handleEndChange" class="picker-view" 
						:indicatorStyle="`height: ${ itemHeight }px;`"
						:style="`height: ${ itemHeight * visibleItemCount }px;width: 300rpx;`"
					>
                        <picker-view-column class="picker-view-column">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="(h, i) in hours" :key="i">
								<text  class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ h }}时</text>
							</view>
                        </picker-view-column>
                        <picker-view-column class="picker-view-column">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="(m, i) in minutes" :key="i">
								<text  class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ m }}分</text>
							</view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>
        </view>
    </up-popup>
</template>

<script>
// 生成时间数组
const range = (start, end, step = 1) => {
    return Array.from({ length: (end - start) / step + 1 }, (_, i) => start + i * step);
};

/**
 * deepseek 帮写的范围时间范围选择器
 * time-range-picker
 * @property {Number}	itemHeight			各列中，单个选项的高度，单位px（默认 44 ）
 * @property {Number}	visibleItemCount	每列中可见选项的数量（默认 5 ）
 */
export default {
    props: {
        show: {
            type: Boolean,
            default: false
        },
        defaultValue: {
            type: Array,
            default: () => ['09:00', '18:00']
        },
        step: {
            type: Number,
            default: 1,
            validator: (v) => [1, 5, 10, 15, 20, 30].includes(v)
        },
        title: {
            type: String,
            default: '选择时间范围'
        },
		itemHeight: {
			type: Number,
			default: 44
		},
		visibleItemCount: {
			type: Number,
			default: 6
		}
    },

    data() {
        return {
            hours: range(0, 23),
            minutes: range(0, 59, this.step),
            startIndex: [0, 0],
            endIndex: [0, 0]
        };
    },

    computed: {
        // 当前开始时间
        startTime() {
            return this.formatTime(this.startIndex);
        },
        // 当前结束时间
        endTime() {
            return this.formatTime(this.endIndex);
        }
    },

    watch: {
        show(val) {
            if (val) this.initDefaultTime();
        }
    },

    mounted() {
        this.initDefaultTime();
    },

    methods: {
        // 初始化默认时间
        initDefaultTime() {
            const parseTime = (timeStr) => {
                const [h, m] = timeStr.split(':');
                return {
                    hour: parseInt(h),
                    minute: parseInt(m)
                };
            };

            const start = parseTime(this.defaultValue[0]);
            const end = parseTime(this.defaultValue[1]);

            this.startIndex = [this.hours.indexOf(start.hour), this.minutes.indexOf(this.nearestStep(start.minute))];

            this.endIndex = [this.hours.indexOf(end.hour), this.minutes.indexOf(this.nearestStep(end.minute))];
        },

        // 处理开始时间变化
        handleStartChange(e) {
            this.startIndex = e.detail.value;
            this.checkTimeValid();
        },

        // 处理结束时间变化
        handleEndChange(e) {
            this.endIndex = e.detail.value;
            this.checkTimeValid();
        },

        // 时间有效性验证
        checkTimeValid() {
            const start = this.timeToMinutes(this.startIndex);
            const end = this.timeToMinutes(this.endIndex);
            return end > start;
        },

        // 确认选择
        handleConfirm() {
            if (!this.checkTimeValid()) {
                uni.showToast({
                    title: '结束时间必须晚于开始时间',
                    icon: 'none'
                });
                return;
            }

            this.$emit('confirm', [this.startTime, this.endTime]);
            // this.closePicker();
        },

        // 关闭弹窗
        closePicker() {
            // this.$emit('update:show', false);
            this.$emit('close');
        },

        // 时间转分钟数
        timeToMinutes([hourIdx, minuteIdx]) {
            return this.hours[hourIdx] * 60 + this.minutes[minuteIdx];
        },

        // 时间格式化
        formatTime([hourIdx, minuteIdx]) {
            const h = this.hours[hourIdx].toString().padStart(2, '0');
            const m = this.minutes[minuteIdx].toString().padStart(2, '0');
            return `${h}:${m}`;
        },

        // 对齐步长
        nearestStep(minute) {
            return Math.round(minute / this.step) * this.step;
        }
    }
};
</script>

<style lang="scss" scoped>
.time-range-container {
	display: flex;
	flex-direction: column;
    background: #fff;

    .picker-header {
        display: flex;
        justify-content: space-between;
		flex-direction: row;
        align-items: center;
        padding: 24rpx 32rpx;
        border-bottom: 1rpx solid #eee;

        .title {
            font-size: 34rpx;
            color: #333;
            font-weight: 500;
        }

        .btn {
            padding: 8rpx 24rpx;
            font-size: 30rpx;

            &.cancel {
                color: #999;
            }

            &.confirm {
                color: #2979ff;
            }
        }
    }

    .picker-body {
        display: flex;
        align-items: center;
		flex-direction: row;
        padding: 40rpx 0;

        .time-picker {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;

            .picker-label {
                color: #666;
                font-size: 28rpx;
                margin-bottom: 15rpx;
            }
			
			.picker-view {
				position: relative;
				.picker-view-column{
					/* #ifdef APP-NVUE */
					flex: 1;
					/* #endif */
					display: flex;
					flex-direction: column;
					justify-content: center;
					.picker-view-column-view{
						display: flex;
						align-items: center;
						justify-content: center;
						margin: 0;
						padding: 0;
						.picker-item {
							margin: 0;
							padding: 0;
						    font-size: 32rpx;
						    color: #333;
						}
					}
				}
			}
        }

        .separator {
            margin: 0 32rpx;
            color: #666;
            font-size: 32rpx;
        }

        

        
    }
}
</style>
